package com.topc.participant.service.impl;

import com.topc.base.constant.RedisConstant;
import com.topc.base.exception.Asserts;
import com.topc.core.sevice.RedisService;
import com.topc.participant.service.IEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class EmailServiceImpl implements IEmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    private TemplateEngine templateEngine;



    @Override
    public void sendPassword(String type,String email, String password, String name) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
            minehelper.setFrom(username); //设置发送邮件账号
            minehelper.setTo(email); //设置接收邮件的人，可以多个
            minehelper.setSubject("欢迎使用Topc OJ系统,这是您的初始密码"); //设置发送邮件的主题
            Context context = new Context();
            context.setVariable("title","初始密码发布");
            context.setVariable("password",password);
            context.setVariable("type",type);
            context.setVariable("name",name);
            String thymeleaf = templateEngine.process("/sendInitPwdMail", context);
            minehelper.setText(thymeleaf,true); //设置发送邮件的内容 第二个设置为true则可以发送带HTML的邮件
            mailSender.send(message);
        } catch (MessagingException e) {
            Asserts.fail("邮件发送失败");
        }
    }
}
